
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xreader/app/app_routes.dart';
import 'package:xreader/logs/log.dart';
import 'package:xreader/model/t_book_cont_entity.dart';
import 'package:xreader/model/t_book_entity.dart';
import 'package:xreader/novel/view/reader/novel_reader_page.dart';
import 'package:xreader/pages/widgets/text/brn_expandable_text.dart';
import 'package:xreader/service/book_service.dart';

class BookDetailPage extends StatefulWidget {

  const BookDetailPage({Key? key}) : super(key: key);

  @override
  State<BookDetailPage> createState() => _BookDetailPageState();
}

class _BookDetailPageState extends State<BookDetailPage> {
  late final TBookEntity bookInfo;
  List<TBookContEntity> chapters = [];
  @override
  void initState() {
    var args = Get.arguments;
    bookInfo = args  is TBookEntity ? args : TBookEntity();
    if(bookInfo.bdesc == null || bookInfo.bdesc!.isEmpty){
      bookInfo.bdesc = "暂无详细简介";
    }
    Log.i("书籍参数==> ${bookInfo}");
    _loadChapters(bookInfo);
    super.initState();
  }
  //加载章节
  _loadChapters(TBookEntity bookInfo) async {
    List<TBookContEntity> datas  = await BookService.getChapters(bookInfo);
    Log.i("bookName=${bookInfo.bname} 章节数量=${datas.length}");
    setState(() {
       chapters.addAll(datas);
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("${bookInfo.bname ?? ''}",overflow: TextOverflow.ellipsis,),
        centerTitle: true,
      ),
      body: Stack(
        children: [
          CustomScrollView(
            physics: const BouncingScrollPhysics(),
            slivers: [
              const _DetailTitle("简介"),
              SliverToBoxAdapter(
                child: Container(
                  padding:  EdgeInsets.symmetric(vertical: 10, horizontal:15),
                  child: BrnExpandableText(
                    textStyle:TextStyle(
                                fontSize: 17,
                                color: Colors.black54,
                     ),
                    text: bookInfo.bdesc ?? "",
                    maxLines: 6,
                  ),
                ),
              ),
              const SliverToBoxAdapter(
                child: Divider(
                  height: 1,
                  color: Colors.black12,
                ),
              ),
              chapters.length > 0 ? _DetailTitle("目录 共${chapters.length}节") : _DetailTitle("目录"),
              SliverToBoxAdapter(
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                      maxHeight: MediaQuery.of(context).size.height / 1.5),
                  child: ListView.separated(
                      padding: EdgeInsets.symmetric(horizontal: 16),
                      itemBuilder: (ctx,index){
                        TBookContEntity chapterInfo = chapters[index];
                        String btitle = chapterInfo.btitle ?? "";
                        int bnum = chapterInfo.bnum ?? 0;
                        ListTile itemEle = ListTile(
                          //leading: const Icon(Icons.article_outlined),
                          title: Text(btitle,style: TextStyle(fontSize: 16),),
                          subtitle: bnum > 0 ? Text("${bnum}字") : null,
                          leading: Badge(
                            label: Text("${index+1}"),
                            backgroundColor: Colors.black87,
                          ),
                          onTap: (){
                            Log.i(chapterInfo);
                            //Get.toNamed(AppRoutes.BOOK_READER,arguments:chapterInfo);
                            Get.to(()=>NovelReaderPage(chapterInfo.bookid ?? 0, chapterInfo.id ?? 0));
                          },
                        );
                        return itemEle;
                        // return Container(
                        //   padding: EdgeInsets.symmetric(vertical: 8,horizontal: 8),
                        //   child: Text(
                        //     btitle,
                        //   ),
                        // );
                      },
                      separatorBuilder: (ctx,index){
                        return Divider(height: 1,);
                      },
                      itemCount: chapters.length
                  ),
                ) ,
              )
            ],
          )
        ],
      ),
    );
  }
}

class _DetailTitle extends StatelessWidget {
  final String title;
  const _DetailTitle(this.title,{Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.symmetric(vertical:10, horizontal: 15),
        child: Text(
          "${title}",
          softWrap: true,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
      ),
    );
  }
}

class _DetailDesc extends StatelessWidget {
  final String text;
  const _DetailDesc(this.text,{Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        padding:  EdgeInsets.symmetric(vertical: 10, horizontal:15),
        child: Text(
          "${text}",
          softWrap: true,
          style: const TextStyle(
            fontSize: 17,
            color: Colors.black54,
          ),
        ),
      ),
    );
  }
}


